/*
 * Предок
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define N_MAX		100
#define DFS_TREE	(1 << 4)
#define DFS_NOT_TREE	(1 << 5)
#define COLOR_WHITE	0
#define COLOR_GRAY	1
#define COLOR_BLACK	2

struct Node {
	int x;
	Node *next;
};

struct adjlist {
	Node *first;
	Node *last;
	int8_t size;

	/* Other attributes */
	uint8_t color;
	uint8_t visited;
	int distance;
	unsigned long time_in, time_out;
	int parent;
};


unsigned long timer_ = 0;

static void
pushback(struct adjlist *al, int x)
{
	Node *newnode;

	newnode = (Node *) malloc(sizeof (Node));
	newnode->x = x;
	newnode->next = NULL;
	if (!al->first)
		al->first = newnode;
	else
		al->last->next = newnode;
	al->last = newnode;
	al->size++;
}

static void
free_al(struct adjlist *al)
{
	struct Node *n, *p;
	p = n = al->first;
	while (n) {
		n = n->next;
		free(p);
		p = n;
	}
}

int
dfs_markup_times(struct adjlist *al, const int n, const int r)
	/*
	   r - root index
	 */
{
	Node *node = NULL;

	al[r].visited = 1;
	node = al[r].first;

	timer_++;
	al[r].time_in = timer_;
	fprintf(stderr, "AL[%d].time_in=%lu\n", r, al[r].time_in);

	while (node) {
		if (!al[node->x].visited)
			dfs_markup_times(al, n, node->x);
		node = node->next;
	}

	timer_++;
	al[r].time_out = timer_;
	fprintf(stderr, "AL[%d].time_out=%lu\n", r, al[r].time_out);

	return 0;
}

int
main(void)
{
	struct adjlist *AL;
	int	n, m;
	register int i = 0;
	int	parent_idx,
		root_idx;
	int	a, b;

	(void) scanf("%d", &n);
	AL = (struct adjlist *) calloc(n, sizeof *AL);
	for (i = 0; i < n; i++) {
		(void) scanf("%d", &parent_idx);
		parent_idx--;
		AL[i].parent = parent_idx;
		if (parent_idx == -1)
			root_idx = i;
		else
			pushback(&AL[parent_idx], i);
	}
	dfs_markup_times(AL, n, root_idx);
	(void) scanf("%d", &m);
	for (i = 0; i < m; i++) {
		(void) scanf("%d %d", &a, &b);
		a--; b--;
		/* is 'a' parent of 'b' ? */
		if (AL[a].time_in  < AL[b].time_in &&
		    AL[b].time_out < AL[a].time_out) {
			puts("1");
		} else {
			puts("0");
		}
	}

out:
	for (i = 0; i < n; i++)
		free_al(&AL[i]);
	free(AL);
	return (0);
}
